//
//  TranslationVC.m
//  语音翻译合成Demo
//
//  Created by 王鹏宇 on 2018/2/26.
//  Copyright © 2018年 王鹏宇. All rights reserved.
//


#import "TranslationVC.h"

#import <Speech/Speech.h>
#import <AVFoundation/AVFoundation.h>

#import <CommonCrypto/CommonDigest.h>
#import "TranslateLeftCell.h"
#import "TranslateRightCell.h"
#import "SelectViewController.h"
#import "TranslationModel.h"
#import "LanguageModel.h"
#import "RippleView.h"
#import "TranslationManager.h"
#import "Const_OC.h"


#define kDocumentPath [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject]

#define RecordViewWidth (300 * kScreenWidth/375)
#define Width (130 * kScreenWidth / 375)
@interface TranslationVC ()<UITableViewDataSource,UITableViewDelegate,UITextFieldDelegate,TranslateCellDelegate>

@property (weak, nonatomic) IBOutlet UIButton *languageBtnLeft;

@property (weak, nonatomic) IBOutlet UILabel *leftLabel;
@property (weak, nonatomic) IBOutlet UILabel *rightLabel;

@property (weak, nonatomic) IBOutlet UIButton *languageBtnRight;

@property (weak, nonatomic) IBOutlet UIButton *exchangeBtn;

@property (weak, nonatomic) IBOutlet UITableView *tableView;

@property (weak, nonatomic) IBOutlet UIButton *recordBtnLeft;

@property (weak, nonatomic) IBOutlet UIButton *recordBtnRight;

@property (weak, nonatomic) IBOutlet UILabel *tipLabel;

@property (weak, nonatomic) IBOutlet UIView *inputView;

@property (weak, nonatomic) IBOutlet UITextField *textFiled;

@property (weak, nonatomic) IBOutlet UIButton *inputLeftBtn;

@property (weak, nonatomic) IBOutlet UIButton *inputRightBtn;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *inputViewLeftSpace;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *inputViewRightSpace;

@property (nonatomic, strong) UIView *recordView;

@property (nonatomic, strong) UILabel *recordTipLabel;

@property (nonatomic, strong) RippleView *recordAnimationView;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *inputViewBottomSpace;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *selectViewTopSpace;


@property (weak, nonatomic) IBOutlet NSLayoutConstraint *recordViewWidth;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *animationViewWidth;

// 辅助属性
@property (nonatomic, copy) NSString *language1;//语音识别 左
@property (nonatomic, copy) NSString *language2;//语音识别 右

@property (nonatomic, copy) NSString *speechLanguage;//语音合成语言
@property (nonatomic, copy) NSString *language;//要翻译语言
@property (nonatomic, copy) NSString *translate;//翻译目标语言

@property (nonatomic, strong)LanguageModel *langModel1;
@property (nonatomic, strong)LanguageModel *langModel2;

// 录音
@property (nonatomic, strong) AVAudioRecorder *recorder;

// 语音合成
@property (nonatomic, strong) AVSpeechSynthesizer *synthesizer;
@property (nonatomic, strong) AVSpeechSynthesisVoice *voice;

@property (nonatomic, strong)NSMutableArray *dataSoure;

@property (nonatomic, strong)TranslationModel *model;

@property (nonatomic, strong)UIView * maskView;

@property (nonatomic, assign)BOOL isRecording;

@property (nonatomic, strong) NSURLSessionDataTask *task;

@property (nonatomic, assign) BOOL isRecordOk;

@property (nonatomic, assign) BOOL isRecognizerOk;

@end

@implementation TranslationVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    self.inputView.hidden = YES;
    self.inputViewBottomSpace.constant = -60;
    self.selectViewTopSpace.constant = kNavigationBarHeight;
    
//    let backItem = UIBarButtonItem(image: UIImage(named: "back"), style: .plain, target: self, action: #selector(backAction))
//
//    self.navigationItem.leftBarButtonItem = backItem
//
//    self.navigationController?.interactivePopGestureRecognizer?.delegate = nil
    
    [self setupOCVC];
    
    [self setup];
    
    AVAudioSession *audioSession = [AVAudioSession sharedInstance];
    [audioSession setCategory:AVAudioSessionCategoryPlayAndRecord withOptions:AVAudioSessionCategoryOptionDefaultToSpeaker error:nil];
    [audioSession setActive:YES error:nil];

    [audioSession requestRecordPermission:^(BOOL granted) {
        if (granted) {
            self.isRecordOk = true;
        }
        else {
            self.isRecordOk = false;
        }
    }];
    [self checkAllThings];
    
    [self initAuth];
}

- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    
    if (self.dataSoure.count > 1) {
        NSIndexPath * indexPath = [NSIndexPath indexPathForRow:self.dataSoure.count - 1 inSection:0];
        [self.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];
    }
    
}

- (void)checkAllThings{
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0) {
        
        
        AVAudioSessionRecordPermission permissionStatus = [[AVAudioSession sharedInstance] recordPermission];
        
        switch (permissionStatus) {
            case AVAudioSessionRecordPermissionUndetermined:{
                NSLog(@"第一次调用，是否允许麦克风弹框");
                [[AVAudioSession sharedInstance] requestRecordPermission:^(BOOL granted) {
                    if (granted) {
                        self.isRecordOk = true;
                    }
                    else {
                        self.isRecordOk = false;
                    }
                }];
                break;
            }
            case AVAudioSessionRecordPermissionDenied:
                self.isRecordOk = false;
                
                break;
            case AVAudioSessionRecordPermissionGranted:
                self.isRecordOk = true;
                break;
            default:
                break;
        }
        if(permissionStatus == AVAudioSessionRecordPermissionUndetermined) return;
    }
    

    
}

- (void)viewWillDisappear:(BOOL)animated {
    
    [super viewWillDisappear:animated];
    
    [TranslationManager sharedManager].translationArray = self.dataSoure;
    [TranslationManager sharedManager].languageLeft = self.langModel1;
    [TranslationManager sharedManager].languageRight = self.langModel2;
    
}

- (void)initAuth {
    
    if (@available(iOS 10.0, *)) {
        
        [SFSpeechRecognizer requestAuthorization:^(SFSpeechRecognizerAuthorizationStatus status) {
            dispatch_async(dispatch_get_main_queue(), ^{
                switch (status) {
                    case SFSpeechRecognizerAuthorizationStatusNotDetermined:
                    case SFSpeechRecognizerAuthorizationStatusDenied:
                    case SFSpeechRecognizerAuthorizationStatusRestricted:
                        self.isRecognizerOk = false;
                        break;
                        
                    case SFSpeechRecognizerAuthorizationStatusAuthorized:
                       self.isRecognizerOk = true;
                        break;
                    default:
                        break;
                }
            });
        }];
    } else {
        
        [self makeToastWithText:@"系统版本过低，不支持翻译"];
        
    }
    
    
}

- (UIView *)maskView{
    
    if (!_maskView) {
        _maskView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight - 140)];
        _maskView.backgroundColor = [UIColor colorWithWhite:0 alpha:0.6];
        
        [_maskView addSubview:self.recordView];
        self.recordView.center = _maskView.center;
    }
    return _maskView;
}

- (UIView *)recordView {
    
    if (!_recordView) {
        
        _recordView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, RecordViewWidth, RecordViewWidth/3 *2)];
        _recordView.layer.cornerRadius = 5;
        _recordView.clipsToBounds = YES;
        _recordView.backgroundColor = [UIColor whiteColor];
        _recordAnimationView = [[RippleView alloc] initWithFrame:CGRectMake(0, 0, Width, Width)];
        [_recordView addSubview:_recordAnimationView];
        _recordAnimationView.center = CGPointMake(_recordView.center.x, _recordView.center.y - 25);
        
        UIImageView * imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"translation麦克"]];
        [_recordAnimationView addSubview:imageView];
        imageView.center = CGPointMake(Width/2,Width/2);
        
        _recordTipLabel = [[UILabel alloc] init];
        _recordTipLabel.textColor = KThemeColor;
        _recordTipLabel.font = [UIFont systemFontOfSize:14];
        _recordTipLabel.textAlignment = NSTextAlignmentCenter;
        _recordTipLabel.text = LocalizedString(@"swip_cancel_trans");
        [_recordView addSubview:_recordTipLabel];
        
        
        _recordTipLabel.frame = CGRectMake(CGRectGetMinX(self.recordView.frame),
                                           CGRectGetMaxY(self.recordAnimationView.frame),
                                           CGRectGetWidth(self.recordView.frame),
                                           CGRectGetHeight(self.recordView.frame) -CGRectGetMaxY(self.recordAnimationView.frame));
        
    }
    
    return _recordView;
}
- (NSMutableArray *)dataSoure {
    
    if (!_dataSoure) {
        
        if ([TranslationManager sharedManager].translationArray) {
            _dataSoure = [NSMutableArray arrayWithArray:[TranslationManager sharedManager].translationArray];
        }else{
            _dataSoure = [[NSMutableArray alloc] init];
        }
        
    }
    return _dataSoure;
}
- (void)dealloc{
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    
}
- (void)setLangModel1:(LanguageModel *)langModel1{
    _langModel1 = langModel1;
    self.language1 = langModel1.lang;
    self.leftLabel.text = LocalizedString(langModel1.name_local);
    [self.recordBtnLeft setTitle:LocalizedString(langModel1.name_local) forState:UIControlStateNormal];
}

- (void)setLangModel2:(LanguageModel *)langModel2{
    _langModel2 = langModel2;
    self.language2 = langModel2.lang;
    self.rightLabel.text = LocalizedString(langModel2.name_local);
    [self.recordBtnRight setTitle:LocalizedString(langModel2.name_local) forState:UIControlStateNormal];
}

- (void)setup {
    
    self.title = LocalizedString(@"speech_tans");
    self.tipLabel.text = LocalizedString(@"press_to_speech");
    self.textFiled.delegate = self;
    self.textFiled.returnKeyType = UIReturnKeySend;
    self.textFiled.placeholder = LocalizedString(@"trans_placeholder");
    
    self.leftLabel.font = [UIFont systemFontOfSize:14];
    self.rightLabel.font = [UIFont systemFontOfSize:14];
    self.leftLabel.textColor = kSubitleColor;
    self.rightLabel.textColor = kSubitleColor;
    [self.recordBtnLeft setBackgroundColor:KThemeColor];
    [self.recordBtnRight setBackgroundColor:kThemeRedColor];
    
    [self.languageBtnLeft setTitleColor:kSubitleColor forState:UIControlStateNormal];
    [self.languageBtnRight setTitleColor:kSubitleColor forState:UIControlStateNormal];
    self.tipLabel.textColor = kContentColor;
    
    [self.tableView registerNib:[UINib nibWithNibName:@"TranslateLeftCell" bundle:nil] forCellReuseIdentifier:@"TranslateLeftCell"];
    
    [self.tableView registerNib:[UINib nibWithNibName:@"TranslateRightCell" bundle:nil] forCellReuseIdentifier:@"TranslateRightCell"];
    
    //    [self rightBarButtonWithImageName:@"删除" selector:@selector(deleteHistory)];
    UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"删除"] style:UIBarButtonItemStylePlain target:self action:@selector(deleteHistory)];
    self.navigationItem.rightBarButtonItem = item;
    
    //注册键盘弹出通知
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillShow:)
                                                 name:UIKeyboardWillShowNotification
                                               object:nil];
    //注册键盘隐藏通知
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillHide:)
                                                 name:UIKeyboardWillHideNotification
                                               object:nil];
    
    
    self.langModel1 = [TranslationManager sharedManager].languageLeft;
    self.langModel2 = [TranslationManager sharedManager].languageRight;
    self.model = [[TranslationModel alloc] init];
}


- (IBAction)LanguageLeftBtnClicked:(UIButton *)sender {
    
    [self.textFiled endEditing:YES];
    SelectViewController *vc =  [[SelectViewController alloc] init];
    vc.type = 1;
    __weak __typeof__(self) weakself = self;
    vc.block = ^(LanguageModel *lang){
        __strong __typeof(weakself) strongSelf = weakself;
        strongSelf.langModel1 = lang;
        
    };
    vc.currentLanguage = self.language1;
    vc.seletedLanguagel = self.language2;
    [self.navigationController pushViewController:vc animated:YES];
}


- (IBAction)languageRightBtnClicked:(UIButton *)sender {
    [self.textFiled endEditing:YES];
    SelectViewController *vc =  [[SelectViewController alloc] init];
    vc.type = 2;
    __weak __typeof__(self) weakself = self;
    vc.block = ^(LanguageModel *lang) {
        __strong __typeof(weakself) strongSelf = weakself;
        strongSelf.langModel2 = lang;
    };
    vc.currentLanguage = self.language2;
    vc.seletedLanguagel = self.language1;
    [self.navigationController pushViewController:vc animated:YES];
}


- (IBAction)inputLanguageBtnLeftClicked:(UIButton *)sender {
    
    self.language = self.langModel1.translation;
    self.translate = self.langModel2.translation;
    self.inputViewLeftSpace.constant = 60;
    self.inputViewRightSpace.constant = 20;
    [self.textFiled becomeFirstResponder];
    self.model.directionNum = 1;
    self.model.languageType = self.language1;
    self.model.language_local = self.langModel1.name_local;
    self.speechLanguage = self.language2;
}

- (IBAction)inputLanguageBtnRightClicked:(id)sender {
    
    self.language = self.langModel2.translation;
    self.translate = self.langModel1.translation;
    
    self.inputViewLeftSpace.constant = 20;
    self.inputViewRightSpace.constant = 60;
    [self.textFiled becomeFirstResponder];
    self.speechLanguage = self.language1;
    self.model.languageType = self.language2;
    self.model.language_local = self.langModel2.name_local;
    self.model.directionNum = 2;
}
- (IBAction)touchDownRecordLft:(UIButton *)sender {
    
    if (![self isOK]) {
        return;
    }
    
    if (!_isRecording) {
        self.language = self.langModel1.translation;
        self.translate = self.langModel2.translation;
        self.model.language_local = self.langModel1.name_local;
        
        [self record];
        [self startAnimation];
        self.tipLabel.text = LocalizedString(@"unpress_to_stop");
        [self.recordBtnLeft setBackgroundColor: [UIColor hexStringToColorWithHexString:@"#01A1C5"]];
        _recordTipLabel.text = LocalizedString(@"swip_cancel_trans");
        self.isRecording = YES;
    }
    
}

- (BOOL)isOK{
    
    if(!self.isRecognizerOk || !self.isRecordOk){
        
        NSString * str = @"相关权限未设置";
        if (!self.isRecordOk && !self.isRecognizerOk){
            str = @"麦克风和语音识别权限未授权，无法进行语音翻译";
        }else if(!self.isRecordOk && self.isRecognizerOk){
            str = @"麦克风权限未授权，无法进行语音翻译";
        }else if(self.isRecordOk && !self.isRecognizerOk){
            str = @"语音识别权限未授权，无法进行语音翻译";
        }
        
      UIAlertController * alertVC  =  [UIAlertController alertControllerWithTitle:@"" message:str preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction * goAction = [UIAlertAction actionWithTitle:@"去设置" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
            NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
            if ([[UIApplication sharedApplication]canOpenURL:url]) {
                [[UIApplication sharedApplication]openURL:url];
            }
        }];
        
        UIAlertAction * cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
        
        [alertVC addAction:cancelAction];
        [alertVC addAction:goAction];
        
        
        [self presentViewController:alertVC animated:true completion:nil];
        
        return false;
    }else{
        return true;
    }
    
}


- (IBAction)leftCancel:(UIButton *)sender {
    self.tipLabel.text = LocalizedString(@"press_to_speech");
    [self.recorder stop];
    [self stopAnimation];
    _recordTipLabel.text = LocalizedString(@"swip_cancel_trans");
    [self.recordBtnLeft setBackgroundColor:KThemeColor];
}



- (IBAction)rightCancel:(UIButton *)sender {
    
    self.tipLabel.text = LocalizedString(@"press_to_speech");
    _recordTipLabel.text = LocalizedString(@"swip_cancel_trans");
    [self.recordBtnRight setBackgroundColor:kThemeRedColor];
    [self.recorder stop];
    [self stopAnimation];
}

- (IBAction)recordBtnLeftCliked:(UIButton *)sender {
    
    
    __weak __typeof__(self) weakself = self;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        __strong __typeof(weakself) strongSelf = weakself;
        strongSelf.recordBtnLeft.userInteractionEnabled = YES;
    });
    self.model.directionNum = 1;
    self.speechLanguage = self.language2;
    self.model.languageType = self.language1;
    [self speechRecognitionWithLanguage:self.language1];
    [self stopAnimation];
    self.tipLabel.text = LocalizedString(@"press_to_speech");
    [self.recordBtnLeft setBackgroundColor:KThemeColor];
    self.isRecording = NO;
    self.recordBtnLeft.userInteractionEnabled = NO;
}


- (IBAction)touchDownRecordRight:(UIButton *)sender {
    
    if (![self isOK]) {
        return;
    }
    
    if (!_isRecording) {
        self.language = self.langModel2.translation;
        self.translate = self.langModel1.translation;
        self.model.language_local = self.langModel2.name_local;
        [self record];
        [self startAnimation];
        self.tipLabel.text = LocalizedString(@"unpress_to_stop");
        [self.recordBtnRight setBackgroundColor:[UIColor hexStringToColorWithHexString:@"#BF3850"]];
        _recordTipLabel.text = LocalizedString(@"swip_cancel_trans");
        self.isRecording = YES;
    }
    
}

- (IBAction)recordBtnRightClicked:(UIButton *)sender {
    
    self.recordBtnRight.userInteractionEnabled = NO;
    __weak __typeof__(self) weakself = self;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        __strong __typeof(weakself) strongSelf = weakself;
        strongSelf.recordBtnRight.userInteractionEnabled = YES;
    });
    self.speechLanguage = self.language1;
    self.model.languageType = self.language2;
    [self speechRecognitionWithLanguage:self.language2];
    self.model.directionNum = 2;
    [self stopAnimation];
    self.tipLabel.text = LocalizedString(@"press_to_speech");
    [self.recordBtnRight setBackgroundColor:kThemeRedColor];
    
    self.isRecording = NO;
}

- (IBAction)hideKeyBorad:(UIButton *)sender {
    
    [self.textFiled endEditing:YES];
    
}
- (IBAction)exchangeLanguage:(UIButton *)sender {
    [self.textFiled endEditing:YES];
    LanguageModel * model = self.langModel1;
    self.langModel1 = self.langModel2;
    self.langModel2 = model;
}

- (void)deleteHistory {
    
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:nil message:LocalizedString(@"delete_trans_record_tips") preferredStyle:UIAlertControllerStyleAlert];
    
    __weak __typeof__(self) weakself = self;
    [alertVC addAction:[UIAlertAction actionWithTitle:LocalizedString(@"delete") style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        __strong __typeof(weakself) strongSelf = weakself;
        [strongSelf.dataSoure removeAllObjects];
        [strongSelf.tableView reloadData];
    }]];
    
    [alertVC addAction:[UIAlertAction actionWithTitle:LocalizedString(@"cancel") style:UIAlertActionStyleCancel handler:nil]];
    
    [self presentViewController:alertVC animated:YES completion:nil];
}

- (NSDictionary *)getAudioSetting {
    NSMutableDictionary *dicM = [NSMutableDictionary dictionary];
    
    [dicM setObject:@(kAudioFormatLinearPCM) forKey:AVFormatIDKey];
    [dicM setObject:[NSNumber numberWithFloat:44100.0] forKey:AVSampleRateKey];
    [dicM setObject:@(2) forKey:AVNumberOfChannelsKey];
    [dicM setObject:@(32) forKey:AVLinearPCMBitDepthKey];
    [dicM setObject:@(YES) forKey:AVLinearPCMIsFloatKey];
    [dicM setObject:[NSNumber numberWithInt:AVAudioQualityHigh] forKey:AVEncoderAudioQualityKey];
    [dicM setObject:@(256000) forKey:AVEncoderBitRateKey];
    
    return dicM;
}


#pragma mark  -- TranslateCellDelegate

- (void)playTheSpeech:(NSString *)str Translation:(NSString *)translationType {
    
    [self speechSynthesisString:str ToLanguage:translationType];
}



- (void)startAnimation {
    
    self.maskView.hidden = NO;
    [[UIApplication sharedApplication].keyWindow addSubview:self.maskView];
    [self.recordAnimationView startAnimation];
}

- (void)stopAnimation {
    
    self.maskView.hidden = YES;
    [self.maskView removeFromSuperview];
    [self.recordAnimationView stopAnimation];
}
#pragma mark  -- 功能

//录音功能
- (void)record{
    
    NSString *urlStr = [NSString stringWithFormat:@"%@/file.caf", kDocumentPath];
    
    if ([[NSFileManager defaultManager] fileExistsAtPath:urlStr]) {
        [[NSFileManager defaultManager] removeItemAtPath:urlStr error:nil];
    }
    
    NSError *error;
    NSURL *url = [NSURL fileURLWithPath:urlStr];
    NSDictionary *setting = [self getAudioSetting];
    self.recorder = [[AVAudioRecorder alloc] initWithURL:url settings:setting error:&error];
    if (error) {
        NSLog(@"error:%@", error);
        return;
    }
    
    self.recorder.meteringEnabled = YES;
    [self.recorder prepareToRecord];
    [self.recorder record];
}

//语音识别成文字
- (void)speechRecognitionWithLanguage:(NSString *)language{
    
    [self.recorder pause];
    NSLocale *local =[[NSLocale alloc] initWithLocaleIdentifier:language];
    if (@available(iOS 10.0, *)) {
        SFSpeechRecognizer *localRecognizer =[[SFSpeechRecognizer alloc] initWithLocale:local];
        
        NSURL *url = [NSURL fileURLWithPath: [NSString stringWithFormat:@"%@/file.caf", kDocumentPath]];
        
        if (!url) return;
        SFSpeechURLRecognitionRequest *res =[[SFSpeechURLRecognitionRequest alloc] initWithURL:url];
        res.shouldReportPartialResults = NO;
        __weak __typeof__(self) weakself = self;
        [localRecognizer recognitionTaskWithRequest:res resultHandler:^(SFSpeechRecognitionResult * _Nullable result, NSError * _Nullable error) {
            __strong __typeof(weakself) strongSelf = weakself;
            if (error) {
                
                [strongSelf makeToastWithText:LocalizedString(@"retry_speech")];
            }else {
                
                [strongSelf translateLanguage1:self.language ToLanguage2:self.translate WithString:result.bestTranscription.formattedString];
            }
        }];
    } else {
        
        [self makeToastWithText:LocalizedString(@"system_not_support")];
    }
}

//文字翻译调用的是百度接口

- (void)translateLanguage1:(NSString *)langguage1 ToLanguage2:(NSString *)language2 WithString:(NSString *)string {
    
    if (string.length == 0) {
        
        [self makeToastWithText:LocalizedString(@"retry_speech")];
        return;
    }
    
    NSString *sign = [NSString stringWithFormat:@"20171205000102273%@123qSus3KPbUHmyf3FboYVM", string];
    NSString *md5 = [self xq_md5:sign];
    
    self.model.languageStr = string;
    self.tipLabel.text = LocalizedString(@"transing");
    [self showActivity];
    
    NSString *urlstr = [[NSString stringWithFormat:@"http://api.fanyi.baidu.com/api/trans/vip/translate?q=%@&from=%@&to=%@&appid=20171205000102273&salt=123&sign=%@", string, langguage1, language2, md5] stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    
    NSURL *url = [NSURL URLWithString:urlstr];
    
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    request.HTTPMethod = @"GET";
    
    NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    
    if (self.task != nil) {
        [self.task cancel];
        self.task = nil;
    }
    
    __weak __typeof__(self) weakself = self;
    self.task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        
        __strong __typeof(weakself) strongSelf = weakself;
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            if (error != nil) {
                
                [strongSelf makeToastWithText:LocalizedString(@"trans_error")];
                strongSelf.tipLabel.text = LocalizedString(@"press_to_speech");
                return;
            }
            
            id json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
            
            NSArray *result = json[@"trans_result"];
            NSString *str = result.firstObject[@"dst"];
            
            TranslationModel * model = [[TranslationModel alloc] init];
            model.languageStr = strongSelf.model.languageStr;
            model.translationStr = str;
            model.directionNum = strongSelf.model.directionNum;
            model.toLanguageType = strongSelf.speechLanguage;
            model.languageType = strongSelf.model.languageType;
            model.language_local = strongSelf.model.language_local;
            [strongSelf hiddenActivity];
            strongSelf.tipLabel.text = LocalizedString(@"press_to_speech");
            [strongSelf.dataSoure addObject:model];
            [strongSelf.tableView reloadData];
            [strongSelf speechSynthesisString:str ToLanguage:self.speechLanguage];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                if (strongSelf.dataSoure.count > 1) {
                    NSIndexPath * indexPath = [NSIndexPath indexPathForRow:strongSelf.dataSoure.count - 1 inSection:0];
                    [strongSelf.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];
                }
            });
        });
        
    }];
    
    [self.task resume];
}

// 根据文字语音合成

- (void)speechSynthesisString:(NSString *)string  ToLanguage:(NSString *)language{
    
    self.voice = [AVSpeechSynthesisVoice voiceWithLanguage:language];
    self.synthesizer = [[AVSpeechSynthesizer alloc] init];
    
    AVSpeechUtterance *utterance = [AVSpeechUtterance speechUtteranceWithString:string];
    utterance.voice = self.voice;
    [self.synthesizer speakUtterance:utterance];
}
#pragma mark  -- UITableViewDataSource,UITableViewDelegate


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataSoure.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    TranslationModel * model = self.dataSoure[indexPath.row];
    
    if (model.directionNum == 1) {
        
        TranslateLeftCell * cell = [tableView dequeueReusableCellWithIdentifier:@"TranslateLeftCell"];
        cell.delegate = self;
        [cell configData:model];
        return cell;
    }else{
        TranslateRightCell * cell = [tableView dequeueReusableCellWithIdentifier:@"TranslateRightCell"];
        cell.delegate = self;
        [cell configData:model];
        return cell;
    }
    return nil;
}


#pragma mark  -- UITextFieldDelegate


- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    
    [textField endEditing:YES];
    NSString *  str = [textField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    if (str.length > 0) {
        
        [self translateLanguage1:self.language ToLanguage2:self.translate WithString:textField.text];
    }
    
    return YES;
}

#pragma mark   键盘弹出

- (void)keyboardWillShow:(NSNotification *)note {
    
    NSDictionary *info = [note userInfo];
    CGSize keyboardSize = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size;
    
    self.inputView.hidden = NO;
    self.inputViewBottomSpace.constant =keyboardSize.height;
    __weak __typeof__(self) weakself = self;
    [UIView animateWithDuration:0.25 animations:^{
        __strong __typeof(weakself) strongSelf = weakself;
        [strongSelf.view layoutIfNeeded];
    }];
}

- (void)keyboardWillHide:(NSNotification *)note {
    
    self.inputViewBottomSpace.constant = -60;
    
    __weak __typeof__(self) weakself = self;
    [UIView animateWithDuration:0.25 animations:^{
        __strong __typeof(weakself) strongSelf = weakself;
        [strongSelf.view layoutIfNeeded];
    } completion:^(BOOL finished) {
        __strong __typeof(weakself) strongSelf = weakself;
        strongSelf.inputView.hidden = YES;
    }];
}

- (NSString *)xq_md5:(NSString *)str {
    
    const char *cStr = [str UTF8String];//转换成utf-8
    
    unsigned char result[16];//开辟一个16字节（128位：md5加密出来就是128位/bit）的空间（一个字节=8字位=8个二进制数）
    
    CC_MD5( cStr, (CC_LONG)strlen(cStr), result);
    /*
     extern unsigned char *CC_MD5(const void *data, CC_LONG len, unsigned char *md)官方封装好的加密方法
     把cStr字符串转换成了32位的16进制数列（这个过程不可逆转） 存储到了result这个空间中
     */
    
    return  [[NSString stringWithFormat:
              
              @"%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X",
              
              result[0], result[1], result[2], result[3],
              
              result[4], result[5], result[6], result[7],
              
              result[8], result[9], result[10], result[11],
              
              result[12], result[13], result[14], result[15]
              
              ] lowercaseString];
}
@end




